//
//  DISProfitViewController.m
//  Distributor
//
//  Created by 主事丫环 on 2019/5/5.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "DISProfitViewController.h"
#import "YXRunStaticBarTableViewCell.h"
#import "DISAProfitList.h"
#import "AprofitListViewController.h"
#import "AprofitSeleListViewController.h"
#import "AIncomeProgressCell.h"

#define DEVICE_WIDTH [UIScreen mainScreen].bounds.size.width
#define DEVICE_HEIGHT [UIScreen mainScreen].bounds.size.height
#define HFrame(X,Y,W,H) CGRectMake((X),(Y),(W),(H))

@interface DISProfitViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    CGFloat CellWidth;
    NSInteger CellNumber;
    NSInteger currentCell;
}
@property (nonatomic,strong) UITableView *scrollTableView;
@property (nonatomic,strong) NSMutableArray *muarr;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myheight;
//@property (weak, nonatomic) IBOutlet UIView *zhuBGview;
@property (weak, nonatomic) IBOutlet UILabel *todayEar;
@property (weak, nonatomic) IBOutlet UILabel *currentEar;
@property (weak, nonatomic) IBOutlet UILabel *AkkEar;
@property (nonatomic,assign) CGFloat maxflold;
@property (nonatomic,strong) NSString *typeStr;//选择时间类型
@property (weak, nonatomic) IBOutlet UITableView *mytableView;
@property (nonatomic,assign)BOOL first;

@end

@implementation DISProfitViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    if (_muarr) {
        [self requestDetaile];
    }
    
    self.mytableView.dataSource = self;
    self.mytableView.delegate = self;
    [self.mytableView registerClass:[AIncomeProgressCell class] forCellReuseIdentifier:@"AIncomeProgressCell"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (IBAction)seletorTime:(UIButton *)sender {
    
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"选择时间" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    /*
     typedef NS_ENUM(NSInteger, UIAlertActionStyle) {
     UIAlertActionStyleDefault = 0,
     UIAlertActionStyleCancel,         取消按钮
     UIAlertActionStyleDestructive     破坏性按钮，比如：“删除”，字体颜色是红色的
     } NS_ENUM_AVAILABLE_IOS(8_0);
     
     */
    // 创建action，这里action1只是方便编写，以后再编程的过程中还是以命名规范为主
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"本日" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.typeStr = @"day";
        [sender setTitle:@"本日" forState:(UIControlStateNormal)];
        [self requestDetaile];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"本周" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [sender setTitle:@"本周" forState:(UIControlStateNormal)];
        
        self.typeStr = @"wek";
        [self requestDetaile];
    }];
    
    UIAlertAction *action3= [UIAlertAction actionWithTitle:@"本月" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [sender setTitle:@"本月" forState:(UIControlStateNormal)];
        
        self.typeStr = @"mon";
        [self requestDetaile];
    }];
    UIAlertAction *action4= [UIAlertAction actionWithTitle:@"本年" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [sender setTitle:@"本年" forState:(UIControlStateNormal)];
        
        self.typeStr = @"yea";
        [self requestDetaile];
    }];
    
    UIAlertAction *action5 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    //把action添加到actionSheet里
    [actionSheet addAction:action1];
    [actionSheet addAction:action2];
    [actionSheet addAction:action3];
    [actionSheet addAction:action4];
    [actionSheet addAction:action5];
    [self presentViewController:actionSheet animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.typeStr = @"wek";
    
    if (IPHONE_X) {
        self.myheight.constant = 286+44;
    }else{
        self.myheight.constant = 286-24;
    }
    self.muarr = [NSMutableArray arrayWithCapacity:1];
    
    self.first = YES;
    [self requestDetaile];
}


-(void)requestDetaile{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"dateType"] = _typeStr;
    
    [NetWorkTool POST:shouyeShouyiApi param:param success:^(id dic) {
      
        [self.muarr removeAllObjects];
        NSDictionary *mydic = [dic objectForKey:@"data"];
        self.AkkEar.text = [NSString stringWithFormat:@"%@",[mydic objectForKey:@"AllEar"]];
        self.currentEar.text = [NSString stringWithFormat:@"%@",[mydic objectForKey:@"currentEar"]];
        self.todayEar.text = [NSString stringWithFormat:@"%@",[mydic objectForKey:@"todayEar"]];
        
        for (NSDictionary *moDic in [mydic objectForKey:@"list"]) {
            DISAProfitList *model = [[DISAProfitList alloc]init];
            [model setValuesForKeysWithDictionary:moDic];
            
            CGFloat ffff = [model.earning floatValue];
            if (ffff>self.maxflold) {
                self.maxflold = ffff;
            }
            [self.muarr addObject:model];
        }
        if (self.first) {
            self.maxflold+=30;
            self.first = NO;
        }
        
        [self initData];
        [self.mytableView reloadData];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        [self.muarr removeAllObjects];
        [self initData];
        [self.mytableView reloadData];
    } fail:^(NSError *error) {
        [self.muarr removeAllObjects];
        [self initData];
        [self.mytableView reloadData];
    } needUser:YES];
}

- (void)initData {
    CellNumber = 6;
    CellWidth = DEVICE_WIDTH;
    currentCell = 0;
}

-(void)showtab{

    UITableView *scrollTableView = [UITableView new];
    scrollTableView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    scrollTableView.delegate = self;
    scrollTableView.dataSource = self;
    scrollTableView.rowHeight = CellWidth/CellNumber;
    scrollTableView.showsVerticalScrollIndicator = NO;
    scrollTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    //scrollTableView.backgroundColor = [UIColor cyanColor];
    //scrollTableView.bounces = NO;
    
    _scrollTableView = scrollTableView;
 
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.muarr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *CellIdentitier = [NSString stringWithFormat:@"cell%ld%ld",(long)indexPath.section, indexPath.row];
    AIncomeProgressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentitier];
    if (!cell) {
        cell = [[AIncomeProgressCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentitier];
    }
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //对Cell进行简单的数据配置
    cell.AkkEar = self.AkkEar.text;
    DISAProfitList *model = [self.muarr safeObjectAtIndex:indexPath.row];
    cell.areanameLabel.text = model.area_name;
    cell.AmountLabel.text = [NSString stringWithFormat:@"%.2f",[model.earning floatValue]];
    
    if (indexPath.row == 0) {
        [cell.headImageView setImage:imgname(@"headerImg001")];
    } else if (indexPath.row == 1) {
        [cell.headImageView setImage:imgname(@"headerImg002")];
    } else if (indexPath.row == 2) {
        [cell.headImageView setImage:imgname(@"headerImg003")];
    } else {
        cell.headImageView.hidden = YES;
        
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.frame = CGRectMake(5, 20, 60, 20);        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.font = FontSize(14);
        titleLab.text = [NSString stringWithFormat:@"%@%ld",@"NO.",(long)indexPath.row + 1];
        titleLab.textColor = [UIColor colorWithHexString:@"#CA9F61"];
        [cell addSubview:titleLab];
    }
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - ScrollViewDelegate

- (CGPoint)nearestContentOffsetForOffset:(CGPoint)offset {
    CGFloat pageSize = CellWidth/CellNumber;
    NSInteger page = round(offset.y / pageSize);
    CGFloat targetY = pageSize * page;
    return CGPointMake(offset.x,targetY);
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGPoint point = [self nearestContentOffsetForOffset:*targetContentOffset];
    targetContentOffset->x = point.x;
    targetContentOffset->y = point.y;
}

//- (BOOL)s
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollTableView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        CGFloat temp = offsetY / (CellWidth/CellNumber);
        
        NSInteger tempNum = [self getRoundValueWithFloat:temp roundingMode:NSRoundPlain scale:0];
        NSLog(@"offsetY:%f   temp:%f   tempNum:%ld",offsetY,temp,tempNum);
        
        currentCell = tempNum + (CellNumber-1)/2;
        [self.scrollTableView reloadData];
    }
}

//四舍五入
- (CGFloat)getRoundValueWithFloat:(CGFloat)value roundingMode:(NSRoundingMode)roundingMode scale:(NSInteger)scale {
    NSDecimalNumberHandler * handler = [[NSDecimalNumberHandler alloc]initWithRoundingMode:roundingMode scale:scale raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber * outNum = [[[NSDecimalNumber alloc]initWithFloat:value] decimalNumberByRoundingAccordingToBehavior:handler];
    return [outNum floatValue];
}

- (IBAction)upAction:(UIButton *)sender {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    AprofitSeleListViewController *shouyiLIst = [[AprofitSeleListViewController alloc]init];
    shouyiLIst.typeSYstr = @"1";
    shouyiLIst.moneyStr = _currentEar.text;
    
    [self.navigationController pushViewController:shouyiLIst animated:YES];
}

- (IBAction)dowLeftAction:(UIButton *)sender {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    AprofitListViewController *shouyiLIst = [[AprofitListViewController alloc]init];
    shouyiLIst.typeSYstr = @"2";
    shouyiLIst.moneyStr = _currentEar.text;
    
    [self.navigationController pushViewController:shouyiLIst animated:YES];
}

- (IBAction)dowRightAction:(UIButton *)sender {
    AprofitListViewController *shouyiLIst = [[AprofitListViewController alloc]init];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    shouyiLIst.typeSYstr = @"3";
    shouyiLIst.moneyStr = _AkkEar.text;
    [self.navigationController pushViewController:shouyiLIst animated:YES];
}

@end
